package org.luxor.commons.security.config.resource;

import org.luxor.commons.security.annotation.EnableOAuth2ResourceServer;
import org.luxor.commons.security.config.DefaultWebSecurityConfigurerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Map;


/**
 * EnableAdminSecurity 注解配置注册器
 *
 * @author lengleng @date 2019/03/08
 */
public class OAuth2ResourceServerBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
    private static final Logger log = LoggerFactory.getLogger(OAuth2ResourceServerBeanDefinitionRegistrar.class);

    /**
     * 根据注解值动态注入资源服务器的相关属性
     *
     * @param metadata 注解信息
     * @param registry 注册器
     */
    @Override
    public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
        Map<String, Object> attrs = metadata.getAnnotationAttributes(EnableOAuth2ResourceServer.class.getName(), false);
        if (attrs == null) {
            return;
        }

        GenericBeanDefinition beanDefinitionOne = new GenericBeanDefinition();
        beanDefinitionOne.setBeanClass(DefaultWebSecurityConfigurerAdapter.class);
        registry.registerBeanDefinition("defaultWebSecurityConfiguration", beanDefinitionOne);

        registerRemoteResourceServerConfigurer(registry);

    }

    private void registerRemoteResourceServerConfigurer(BeanDefinitionRegistry registry) {
        log.info("load OAuth2ResourceServerConfigurer Started...");

        GenericBeanDefinition beanDefinitionOne = new GenericBeanDefinition();
        beanDefinitionOne.setBeanClass(OAuth2ResourceServerConfigurer.class);
        registry.registerBeanDefinition("oAuth2ResourceServerConfigurer", beanDefinitionOne);

        log.info("load OAuth2ResourceServerConfigurer completed.");
    }

}